package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"planet/models"
	"strconv"
	"time"
)

type QuestionController struct {
	beego.Controller
}

type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 提问问题（添加）

func (c *QuestionController) Ask() {
	title := c.GetString("title")
	content := c.GetString("content")
	img := c.GetString("img")
	cateId, _ := c.GetInt("cate_id")
	question := models.Question{
		Title:   title,
		Content: content,
		Img:     img,
		CateId:  uint(cateId),
	}
	err := models.DB.Create(&question).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "发布问题失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "发布问题成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

// 文件上传

func (c *QuestionController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "文件过大",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		imgSrc := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "上传成功",
			Data: imgSrc,
		}
		c.ServeJSON()
	}

}

// 问题分类

func (c *QuestionController) QuestionType() {
	var qt []models.QuestionType
	err := models.DB.Find(&qt).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "分类查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "分类查询成功",
			Data: qt,
		}
		c.ServeJSON()
	}
}

// 分页

func (c *QuestionController) List() {

	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	title := c.GetString("title")
	cateId := c.GetString("cate_id")
	pageData := make(map[string]interface{})
	key := "PAGE:" + strconv.Itoa(page) + ":" + title + ":" + cateId //定义缓存的键
	val, err := models.RedisDB.Get(key).Result()                     //获取缓存
	if err != nil {
		query := models.DB.Model(&models.Question{})
		if title != "" {
			query = query.Where("title like ?", "%"+title+"%")
		}
		if cateId != "" {
			query = query.Where("cate_id = ?", cateId)
		}
		var count int64
		query.Count(&count)         //总数
		offset := (page - 1) * size //偏移量
		var questions []models.Question
		err = query.Preload("QuestionType").Offset(offset).Limit(size).Find(&questions).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			pageData["count"] = count
			pageData["questions"] = questions

			jsonByte, _ := json.Marshal(&pageData)
			value := string(jsonByte)
			models.RedisDB.Set(key, value, time.Second*60) //存入缓存的

			c.Data["json"] = JsonRes{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}

}

// 详情

func (c *QuestionController) Info() {
	id, _ := c.GetInt("id")
	var question models.Question
	err := models.DB.Preload("QuestionType").Where("id = ?", id).First(&question).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "详情展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "详情展示成功",
			Data: question,
		}
		c.ServeJSON()
	}
}

// 查询问题下面的所有答案

func (c *QuestionController) Answers() {
	id, _ := c.GetInt("id")
	var question models.Question
	err := models.DB.Preload("Answers").Preload("QuestionType").Where("id = ?", id).First(&question).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功",
			Data: question,
		}
		c.ServeJSON()
	}
}
